package cn.wizzer.app.web.modules.controllers.platform.sys;

import cn.hutool.core.io.FileUtil;
import cn.wizzer.app.sys.modules.models.SysApk;
import cn.wizzer.app.sys.modules.services.SysApkService;
import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.app.web.commons.ulog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.util.Result;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

@IocBean
@At("/platform/sys/apk")
public class SysApkController {
    private static final Log log = Logs.get();
    @Inject
    @Reference
    private SysApkService sysApkService;
    @Inject
    @Reference
    private SysParamService sysParamService;

    @At("")
    @Ok("beetl:/platform/sys/apk/index.html")
    @RequiresPermissions("sys.manager.apk")
    public void index() {

    }

    @At
    @Ok("json:full")
    @RequiresPermissions("sys.manager.apk")
    public Object data(@Param("pageNumber") Integer pageNumber,
                       @Param("pageSize") Integer pageSize) {
        Sql sql = Sqls.create("SELECT * FROM sys_apk WHERE delFlag = 0 ORDER BY ctAt DESC");
        Sql countSql = Sqls.create("SELECT COUNT(1) FROM sys_apk WHERE delFlag = 0");
        return Result.success().addData(sysApkService.listPage(pageNumber, pageSize, sql, countSql));
    }

    @At
    @Ok("json")
    @RequiresPermissions("sys.manager.apk.add")
    @SLog(tag = "添加apk文件", msg = "${sysApk}")
    public Object add(@Param("..") SysApk sysApk) {
        sysApk.setOpBy(StringUtil.getPlatformUid());
        sysApkService.insert(sysApk);
        return Result.success();
    }

    @At
    @Ok("json")
    @RequiresPermissions("sys.manager.apk.del")
    @SLog(tag = "删除apk文件", msg = "id: ${id}")
    public Object del(@Param("id") String id) {
        SysApk sysApk = sysApkService.fetch(id);
//        SysParam sysParam = sysParamService.fetch();
//        FtpUtil ftpUtil = new FtpUtil(sysParam.getFtpHost(), sysParam.getFtpPort(), sysParam.getFtpUserName(), sysParam.getFtpPassword());
//        ftpUtil.login();
//        boolean result = ftpUtil.deleteFile(sysApk.getFileUploadPath(), sysApk.getFileName());
//        if(!result){
//            return Result.error();
//        }
//        ftpUtil.logOut();
        if (FileUtil.del(sysApk.getFileUploadPath())) {
            sysApkService.vDelete(id);
            return Result.success();
        }
        return Result.error();
    }

}
